package xyz.caijiwang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.caijiwang.entity.User;
import xyz.caijiwang.entity.param.JWTParam;
import xyz.caijiwang.interceptor.TokenNotValidation;
import xyz.caijiwang.response.R;
import xyz.caijiwang.service.LoginService;
import xyz.caijiwang.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginService loginService;

    @TokenNotValidation
    @PostMapping("/login")
    public HashMap<String, String> login(@RequestBody String str) {
        JSONObject strj = JSON.parseObject(str);
        return loginService.getToken(strj.getString("phone"), strj.getString("password"));
    }

    @TokenNotValidation
    @PostMapping("/register")
    public R register(@RequestBody User user) {
        Boolean aBoolean = loginService.checkIsRegisterByPhone(user.getPhone());
        if (aBoolean) {
            return R.fail(400, "对不起，您的手机号已经注册！！");
        }
        user.setRoleid(2);
        user.setCreatdate(new Date());
        loginService.register(user);
        return R.success();
    }


    @GetMapping("/reGetToken")
    public HashMap<String, String> reGetToken(HttpServletRequest request) {
        HashMap<String, String> map = new HashMap<>();
        String token = request.getHeader("Authorization");
        JWTParam param = new JWTParam();
        param.setUserid(JwtUtil.getUserId(token.substring(7)));
        param.setPhone(JwtUtil.getPhone(token.substring(7)));
        param.setRole(JwtUtil.getRole(token.substring(7)));
        param.setAuth(JwtUtil.getAuth(token.substring(7)));
        String sign = JwtUtil.sign(param);
        map.put("info", "success");
        map.put("token", sign);
        return map;
    }
}
